package com.yong.sbd.common.beans.response;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.yong.sbd.common.beans.exception.BusinessException;
import com.yong.sbd.common.beans.exception.CommonExceptionEnum;
import com.yong.sbd.common.beans.exception.RcEnum;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;

/**
 * 相应
 *
 * @author Kang Yong
 * @date 2025/10/22
 * @since 1.0.0
 */
@Getter
@Setter
public class R<T> {

    private Integer code;
    private String msg;
    private T data;

    /**
     * 仅在validate参数校验不通过时有值
     */
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Map<String, String> er;

    private R(Integer code, String msg, T data, Map<String, String> er) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.er = er;
    }

    private R(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> R<T> success() {
        return new R<>(RcEnum.SUCCESS.getCode(), RcEnum.SUCCESS.getMsg());
    }

    public static <T> R<T> success(T data) {
        return new R<>(RcEnum.SUCCESS.getCode(), RcEnum.SUCCESS.getMsg(), data);
    }

    public static <T> R<T> successx(String msg) {
        return new R<>(RcEnum.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> success(Integer code, String msg) {
        return new R<>(code, msg);
    }

    public static <T> R<T> error() {
        return new R<>(RcEnum.FAIL.code, RcEnum.FAIL.msg);
    }

    public static <T> R<T> error(String msg) {
        return new R<>(RcEnum.FAIL.code, msg);
    }

    public static <T> R<T> error(Integer code, String msg) {
        return new R<>(code, msg);
    }

    /**
     * 功能: 通用异常
     *
     * @param exceptionEnum {@link CommonExceptionEnum}
     * @return {@link R<T>}
     * @author KangYong
     * @date 2025/10/22
     */
    public static <T> R<T> error(CommonExceptionEnum exceptionEnum) {
        return new R<>(exceptionEnum.getCode(), exceptionEnum.getMsg());
    }

    /**
     * 功能: 业务异常
     *
     * @param businessException {@link BusinessException}
     * @return {@link R<T>}
     * @author KangYong
     * @date 2025/10/22
     */
    public static <T> R<T> error(BusinessException businessException) {
        return new R<>(businessException.getCode(), businessException.getMessage());
    }

    /**
     * 功能: 参数校验错误
     *
     * @param erMap {@link Map< String, String>}
     * @return {@link  R<T>}
     * @author KangYong
     * @date 2025/10/22
     */
    public static <T> R<T> formError(Map<String, String> erMap) {
        return new R<T>(RcEnum.PARAM_ERROR.getCode(), RcEnum.PARAM_ERROR.getMsg(), null, erMap);
    }

}
